package cn.humaohua.study.hadoop.cmdrunner.c3;

import cn.humaohua.study.hadoop.cmdrunner.Test;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.stereotype.Component;

import java.net.URI;

/**
 * Use the delete() method on FileSystem to permanently remove files or directories
 * public boolean delete(Path f, boolean recursive) throws IOException
 * If f is a file or an empty directory, the value of recursive is ignored.
 * A nonempty directory is deleted, along with its contents, only if recursive is true (otherwise, an IOException is thrown).
 *
 * 如果是文件或空目录，删除时，会忽略recursive。
 * 如果是目录非空，需要recursive=true才可以删除，recursive=false会抛出异常
 */
@Component
public class Rmr implements Test {
    @Override
    public void test() throws Exception {
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create("hdfs://localhost/"), conf);

        //创建测试目录
//        fs.create(new Path("hdfs://localhost/user/hmh/no/use/dirrmr"));


        //1
        //如果目录不为空，下面命令会抛出异常，且不会删除目录
        //Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.fs.PathIsNotEmptyDirectoryException): `/user/hmh/no is non empty': Directory is not empty
//        fs.delete(new Path("hdfs://localhost/user/hmh/no"),false);

        //2 可以删除非空目录
        fs.delete(new Path("hdfs://localhost/user/hmh/no"), true);

        //3 如果第一个参数是一个文件或空目录，递归参数会被忽略
    }
}
